#include "basic_op.h"
#include "common.h"

#include <stdlib.h>
#include <stdio.h>
 
void bittonibble( bit intrans[] , const int n , nibble& outtrans )      //the outtrans is made of the 4 bits of intrans
{
	int i = 0 ;
	outtrans = 0 ;
	for ( i = 0 ; i < n ; ++i )
	{
		outtrans  = outtrans ^ (intrans[i] << i) ;
	}
}

void nibbletobit( nibble intrans , const int n , bit outtrans[] ) 
{
	int i = 0 ;
	for ( i = 0 ; i < n ; ++i )
	{
		outtrans[i] = (intrans >> i) & 0x01 ;
	}
}

void wordtonibble( word intrans , const int n , nibble outtrans[] )
{
	int i = 0 ;
	for ( i = 0 ; i < n ; ++i )
	{
		outtrans[7-i] = (intrans >> (4*i)) & 0x0f ;
	}
}

void nibbletoword( nibble intrans[] , const int n , word& outtrans )
{
	int i = 0 ; 
	outtrans = 0 ;
	for ( i = 0 ; i < n ; ++i )
	{
		outtrans = outtrans ^ (intrans[i]<<(28-4*i)) ;
	}
}

void sbox( nibble insbox[] , const int n , nibble outsbox[] )      //n is equal to 8
{
	int i = 0 ; 
	for ( i = 0 ; i < n ; ++i )
	{
		outsbox[i] = S_BOX[insbox[i]] ;
	}
}

void linear_mix( nibble inmix[] , const int n , nibble outmix[] )
{
	outmix[0] = inmix[1] ^ inmix[2] ^ inmix[3] ^ inmix[4] ^ inmix[5] ^ inmix[6] ;
	outmix[1] = inmix[0] ^ inmix[2] ^ inmix[3] ^ inmix[5] ^ inmix[6] ^ inmix[7] ;
	outmix[2] = inmix[0] ^ inmix[1] ^ inmix[3] ^ inmix[4] ^ inmix[6] ^ inmix[7] ;
	outmix[3] = inmix[0] ^ inmix[1] ^ inmix[2] ^ inmix[4] ^ inmix[5] ^ inmix[7] ;
	outmix[4] = inmix[0] ^ inmix[1] ^ inmix[3] ^ inmix[4] ^ inmix[5] ;
	outmix[5] = inmix[0] ^ inmix[1] ^ inmix[2] ^ inmix[5] ^ inmix[6] ;
	outmix[6] = inmix[1] ^ inmix[2] ^ inmix[3] ^ inmix[6] ^ inmix[7] ;
	outmix[7] = inmix[0] ^ inmix[2] ^ inmix[3] ^ inmix[4] ^ inmix[7] ;
}

void player( nibble inp[] , const int n , nibble outp[] )
{
	int i = 0 ;
	for ( i = 0 ; i < n ; ++i )
	{
		outp[P_LAYER[i]] = inp[i] ;
	}
}

void keyxor( nibble inkey[] , nibble roundkey[] , const int n , nibble outkey[] )
{
	int i = 0 ; 
	for ( i = 0 ; i < n ; ++i )
	{
		outkey[i] = inkey[i] ^ roundkey[i] ;
	}
}

void shiftlayer( bit inshift[] , const int n , int shift_value , bit outshift[] )     //n is equal to 64
{
	int i = 0 ;
	for ( i = 0 ; i < n ; ++i )
	{
		outshift[(i+shift_value)%64] = inshift[i] ;
	}
}

void fputnc( char str[] , int n , FILE* fp ) 
{
	for ( int i = 0 ; i < n ; ++i )
	{
		fputc( str[i] , fp ) ;
	}
}


